package com.atguigu.srb.core.service.impl;

import com.atguigu.srb.core.enums.BorrowInfoStatusEnum;
import com.atguigu.srb.core.enums.BorrowerStatusEnum;
import com.atguigu.srb.core.enums.UserBindEnum;
import com.atguigu.srb.core.mapper.BorrowerMapper;
import com.atguigu.srb.core.mapper.IntegralGradeMapper;
import com.atguigu.srb.core.mapper.UserInfoMapper;
import com.atguigu.srb.core.pojo.entity.BorrowInfo;
import com.atguigu.srb.core.mapper.BorrowInfoMapper;
import com.atguigu.srb.core.pojo.entity.Borrower;
import com.atguigu.srb.core.pojo.entity.IntegralGrade;
import com.atguigu.srb.core.pojo.entity.UserInfo;
import com.atguigu.srb.core.pojo.vo.BorrowInfoApprovalVO;
import com.atguigu.srb.core.pojo.vo.BorrowerDetailVO;
import com.atguigu.srb.core.service.BorrowInfoService;
import com.atguigu.srb.core.service.DictService;
import com.atguigu.srb.core.service.LendService;
import com.atguigu.srb.exception.Assert;
import com.atguigu.srb.result.ResponseEnum;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 借款信息表 服务实现类
 * </p>
 *
 * @author fun
 * @since 2021-10-29
 */
@Service
public class BorrowInfoServiceImpl extends ServiceImpl<BorrowInfoMapper, BorrowInfo> implements BorrowInfoService {
    @Autowired
    UserInfoMapper userInfoMapper;
    @Autowired
    IntegralGradeMapper integralGradeMapper;
    @Autowired
    DictService dictService;
    @Autowired
    BorrowerMapper borrowerMapper;
    @Autowired
    LendService lendService;

    @Override
    public BigDecimal getBorrowAmount(Long userId) {
        //获取用户积分
        UserInfo userInfo = userInfoMapper.selectById(userId);
        Assert.notNull(userInfo, ResponseEnum.LOGIN_MOBILE_ERROR);
        Integer integral = userInfo.getIntegral();

        //根据积分查询借款额度
        QueryWrapper<IntegralGrade> queryWrapper = new QueryWrapper<>();
        queryWrapper.lt("integral_start", integral);
        queryWrapper.ge("integral_end", integral);
        IntegralGrade integralGrade = integralGradeMapper.selectOne(queryWrapper);
        if (integralGrade == null) {
            return new BigDecimal("0");
        }
        return integralGrade.getBorrowAmount();
    }

    @Override
    public Integer getBorrowInfoStatus(Long userId) {
        QueryWrapper<BorrowInfo> borrowInfoQueryWrapper = new QueryWrapper<>();
        borrowInfoQueryWrapper.select("status").eq("user_id", userId);
        List<Object> objects = baseMapper.selectObjs(borrowInfoQueryWrapper);
        if (objects != null && objects.size() > 0) {
            Integer status = (Integer) objects.get(0);
            return status;
        }
        //借款人尚未提交信息
        return BorrowInfoStatusEnum.NO_AUTH.getStatus();
    }

    @Override
    public void saveBorrowInfo(BorrowInfo borrowInfo, Long userId) {
        //获取userInfo的用户数据
        UserInfo userInfo = userInfoMapper.selectById(userId);
        //判断用户绑定状态
        Assert.isTrue(
                userInfo.getBindStatus().intValue() == UserBindEnum.BIND_OK.getStatus().intValue(),
                ResponseEnum.USER_NO_BIND_ERROR);
        //判断用户信息是否审批通过
        Assert.isTrue(
                userInfo.getBorrowAuthStatus().intValue() == BorrowerStatusEnum.AUTH_OK.getStatus().intValue(),
                ResponseEnum.USER_NO_AMOUNT_ERROR);

        //判断借款额度是否足够
        BigDecimal borrowAmount = this.getBorrowAmount(userId);
        Assert.isTrue(
                borrowInfo.getAmount().doubleValue() <= borrowAmount.doubleValue(),
                ResponseEnum.USER_AMOUNT_LESS_ERROR);
        //存储数据
        borrowInfo.setUserId(userId);
        //百分比转成小数
        borrowInfo.setBorrowYearRate(borrowInfo.getBorrowYearRate().divide(new BigDecimal(100)));
        borrowInfo.setStatus(BorrowInfoStatusEnum.CHECK_RUN.getStatus());
        baseMapper.insert(borrowInfo);
    }

    /**
     * 获取借款人列表getBorrowInfoList
     *
     * @return
     */
    @Override
    public List<BorrowInfo> getBorrowInfoList() {
        List<BorrowInfo> borrowInfoList = baseMapper.selectList(null);
        for (BorrowInfo borrowInfo : borrowInfoList) {
            Long userId = borrowInfo.getUserId();
            UserInfo userInfo = userInfoMapper.selectById(userId);
            borrowInfo.setName(userInfo.getName());
            borrowInfo.setMobile(userInfo.getMobile());
            // 其他参数
            Integer returnMethod = borrowInfo.getReturnMethod();
            Integer moneyUse = borrowInfo.getMoneyUse();
            Integer status = borrowInfo.getStatus();
            String returnMethodName = dictService.getNameByParentDictCodeAndValue("returnMethod", returnMethod);
            String moneyUseName = dictService.getNameByParentDictCodeAndValue("moneyUse", moneyUse);

            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("returnMethod", returnMethodName);
            paramMap.put("moneyUse", moneyUseName);
            paramMap.put("status", BorrowInfoStatusEnum.getMsgByStatus(status));
            borrowInfo.setParam(paramMap);
        }

        return borrowInfoList;
    }

    @Override
    public Map<String,Object> getBorrowInfoDetail(Long id) {
        Map<String, Object> map = new HashMap<>();
        BorrowInfo borrowInfo = new BorrowInfo();
        borrowInfo = baseMapper.selectById(id);
        // 其他参数
        Integer returnMethod = borrowInfo.getReturnMethod();
        Integer moneyUse = borrowInfo.getMoneyUse();
        Integer status = borrowInfo.getStatus();
        String returnMethodName = dictService.getNameByParentDictCodeAndValue("returnMethod", returnMethod);
        String moneyUseName = dictService.getNameByParentDictCodeAndValue("moneyUse", moneyUse);

        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("returnMethod",returnMethodName);
        paramMap.put("moneyUse",moneyUseName);
        paramMap.put("status",BorrowInfoStatusEnum.getMsgByStatus(status));
        borrowInfo.setParam(paramMap);


        // 组合数据（借款人信息+借款信息）
        BorrowerDetailVO borrowerDetailVO = new BorrowerDetailVO();
        Long userId = borrowInfo.getUserId();
        QueryWrapper<Borrower> borrowerQueryWrapper = new QueryWrapper<>();
        borrowerQueryWrapper.eq("user_id",userId);
        Borrower borrower = borrowerMapper.selectOne(borrowerQueryWrapper);

        BeanUtils.copyProperties(borrower, borrowerDetailVO);
        // 封装字典数据名
        Integer education = borrower.getEducation();
        String educationName = dictService.getNameByParentDictCodeAndValue("education", education);
        borrowerDetailVO.setEducation(educationName);

        Integer industry = borrower.getIndustry();
        String industryName = dictService.getNameByParentDictCodeAndValue("industry", industry);
        borrowerDetailVO.setIndustry(industryName);

        Integer income = borrower.getIncome();
        String incomeName = dictService.getNameByParentDictCodeAndValue("income", income);
        borrowerDetailVO.setIncome(incomeName);

        Integer relation = borrower.getContactsRelation();
        String relationName = dictService.getNameByParentDictCodeAndValue("relation", relation);
        borrowerDetailVO.setContactsRelation(relationName);

        Integer returnSource = borrower.getReturnSource();
        String returnSourceName = dictService.getNameByParentDictCodeAndValue("returnSource", returnSource);
        borrowerDetailVO.setReturnSource(returnSourceName);

        borrowerDetailVO.setSex(borrower.getSex() == 1 ? "男" : "女");
        borrowerDetailVO.setMarry(borrower.getMarry()? "是" : "否");

        String msgByStatus = BorrowerStatusEnum.getMsgByStatus(borrower.getStatus());
        borrowerDetailVO.setStatus(msgByStatus);

        borrowerDetailVO.setIdCard(borrower.getIdCard().toString());

        map.put("borrowInfo",borrowInfo);
        map.put("borrower",borrowerDetailVO);

        return map;
    }

    @Override
    public void approval(BorrowInfoApprovalVO borrowInfoApprovalVO) {
        // 修改borrowInfo的审核状态
        Integer status = BorrowInfoStatusEnum.CHECK_OK.getStatus();
        Long id = borrowInfoApprovalVO.getId();
        BorrowInfo borrowInfo = new BorrowInfo();
        borrowInfo.setId(id);
        borrowInfo.setStatus(status);
        baseMapper.updateById(borrowInfo);

        // 生成标的信息
        BorrowInfo borrowInfoParam = baseMapper.selectById(borrowInfo.getId());
        if(borrowInfoApprovalVO.getStatus().intValue()==BorrowInfoStatusEnum.CHECK_OK.getStatus().intValue()){
            lendService.creatLend(borrowInfoApprovalVO,borrowInfoParam);
        }
    }
}
